package com.nova.bluetooth.xunFeiSDK.kugouMusic;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.alibaba.fastjson.JSON;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.iflytek.aiui.AIUIAgent;
import com.iflytek.aiui.AIUIConstant;
import com.iflytek.aiui.AIUIEvent;
import com.iflytek.aiui.AIUIListener;
import com.iflytek.aiui.AIUIMessage;
import com.iflytek.aiui.player.common.data.MetaItem;
import com.iflytek.aiui.player.core.AIUIPlayer;
import com.iflytek.aiui.player.core.PlayState;
import com.iflytek.aiui.player.core.PlayerListener;
import com.iflytek.aiui.player.players.TmeMusicRemote;
import com.nova.bluetooth.R;
import com.nova.bluetooth.xunFeiSDK.engine.AiuiEngine;
import com.nova.bluetooth.xunFeiSDK.engine.EngineConstants;
import com.nova.bluetooth.xunFeiSDK.engine.WakeupEngine;
import com.nova.bluetooth.xunFeiSDK.engine.WakeupListener;
import com.nova.bluetooth.xunFeiSDK.recorder.AudioRecorder;
import com.nova.bluetooth.xunFeiSDK.recorder.RecorderFactory;
import com.nova.bluetooth.xunFeiSDK.recorder.SystemRecorder;
import com.nova.bluetooth.xunFeiSDK.utils.CopyAssetsUtils;
import com.nova.bluetooth.xunFeiSDK.utils.FileUtil;
import com.nova.bluetooth.xunFeiSDK.utils.StreamingAsrUtil;
import com.nova.bluetooth.xunFeiSDK.utils.senselessWordUtil;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.nio.charset.StandardCharsets;
import java.util.List;

import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function2;
import timber.log.Timber;

/**
 * 酷狗音乐Demo
 * 功能：唤醒+识别+语义+音乐
 */
public class KugouDemo extends Activity implements OnClickListener {
    private static String TAG = KugouDemo.class.getSimpleName();
    private Toast mToast;
    private EditText mNlpText;
    private AIUIAgent mAIUIAgent = null;
    private TmeMusicRemote mTMERemote = null;
    private AIUIPlayer mAIUIPlayer = null;
    private static String tmeSDKParams = null;
    private static String SONG_NAME = null;
    private boolean isActivated = false;      //是否已激活设备
    private Button ActivatedBtn;      //激活设备按钮
    private Button LoginBtn;          //登录按钮
    private Button LogoutBtn;         //登出按钮
    private Button PreBtn;            //上一首按钮
    private Button NextBtn;           //下一首按钮
    private Button PlayOrStopBtn;     //开始&停止播放
    private Button PauseOrResumeBtn;  //暂停&恢复播放按钮
    private Button EnableWakeupBtn;  //开关语音唤醒
    private boolean EnableWakeup = true;  //开关语音唤醒
    private static int playListIndex = 0; //当前播放歌曲序号
    private static JSONArray mPlayList = null; //播放列表
    private AudioRecorder recorder; //录音机
    private WakeupEngine wakeupEngine;   // 降噪唤醒引擎
    private static String aiuiCfgPath = "";


    @SuppressLint("ShowToast")
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_kugou_demo);
        requestPermissions();
        initLayout();

        // 资源拷贝
        CopyAssetsUtils.portingFile(this);
    }

    @SuppressLint("WrongViewCast")
    private void initLayout() {
        findViewById(R.id.init).setOnClickListener(KugouDemo.this);
        findViewById(R.id.destroy).setOnClickListener(KugouDemo.this);
        findViewById(R.id.startRecord).setOnClickListener(KugouDemo.this);
        findViewById(R.id.stopRecord).setOnClickListener(KugouDemo.this);
        ActivatedBtn = findViewById(R.id.activation);
        LoginBtn = findViewById(R.id.login);
        LogoutBtn = findViewById(R.id.logout);
        PreBtn = findViewById(R.id.last_song);
        NextBtn = findViewById(R.id.next_song);
        PlayOrStopBtn = findViewById(R.id.play_stop);
        PauseOrResumeBtn = findViewById(R.id.pause_resume);
        EnableWakeupBtn = findViewById(R.id.enable_wakeup);
        ActivatedBtn.setOnClickListener(this);
        LoginBtn.setOnClickListener(this);
        LogoutBtn.setOnClickListener(this);
        PreBtn.setOnClickListener(this);
        NextBtn.setOnClickListener(this);
        PlayOrStopBtn.setOnClickListener(this);
        PauseOrResumeBtn.setOnClickListener(this);
        EnableWakeupBtn.setOnClickListener(this);

        mNlpText = findViewById(R.id.nlp_text);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.init) { // 创建SDK对象
            requiresPermission();
        } else if (id == R.id.destroy) { // 销毁SDK对象
            releaseSDK();
        } else if (id == R.id.startRecord) {// 开始语音语义
            startRecord();
        } else if (id == R.id.stopRecord) {// 停止语音语义
            stopVoiceNlp();
        } else if (id == R.id.activation) { //激活酷狗
            activate();
        } else if (id == R.id.login) {   //登录酷狗账号
            login();
        } else if (id == R.id.logout) {  //登录酷狗账号
            logout();
        } else if (id == R.id.last_song) { //上一首
            last();
        } else if (id == R.id.next_song) {//下一首
            next();
        } else if (id == R.id.play_stop) { //播放/停止
            controlPlayOrStop();
        } else if (id == R.id.pause_resume) {  //暂停播放/恢复播放
            controlPauseOrResume();
        } else if (id == R.id.enable_wakeup) {  //开启语音唤醒/禁用语音唤醒
            changeWakeupStatus();
        }
    }

    public void initSDK() {

        //TODO 开发者需要实现生成sn的代码，参考：https://www.yuque.com/iflyaiui/zzoolv/tgftb5
        //注意事项1: sn每台设备需要唯一！！！！WakeupEngine的sn和AIUI的sn要一致
        //注意事项2: 获取的值要保持稳定，否则会重复授权，浪费授权量
        String androidId = Settings.System.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        EngineConstants.serialNumber = "Tang-" + androidId;
        // 设置 TME音乐SDK设置相关参数，appid和appkey请使用自己的进行开发
        tmeSDKParams = "appId=d9467cb9,appKey=d2c176b230653fbe2c61dc7e2db79d21," +
                "serialNumber=" + EngineConstants.serialNumber + ",deviceModel=" + EngineConstants.serialNumber + ",userId=" + EngineConstants.serialNumber;
        mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
        //aiui配置文件在assets下的路径
        aiuiCfgPath = "cfg/aiui_kugouDemo.cfg";
        // 初始化 TMERemote
        createTMEMusicRemote();
        // 初始化AIUIPlayer
        createAIUIPlayer();
        // 初始化AIUI(识别，合成，语义理解)
        initAIUI();
        //初始化CAE(降噪+唤醒)
        wakeupEngine = WakeupEngine.getInstance(wakeupListener);
        if (wakeupEngine != null) {
            setText(mNlpText, "wakeupEngine初始化成功", false);
            Log.i(TAG, "wakeupEngine初始化成功");
        } else {
            setText(mNlpText, "wakeupEngine初始化失败", false);
            Log.e(TAG, "wakeupEngine初始化失败");
        }

        //初始化录音
        if (recorder == null) {
            recorder = RecorderFactory.getRecorder();
        }
        if (recorder != null) {
            setText(mNlpText, "录音机初始化成功", false);
        } else {
            setText(mNlpText, "录音机初始化失败", false);
        }

        setText(mNlpText, "---------------------", false);
        setText(mNlpText, "先开启录音，说“小飞小飞”唤醒，再说“我要听刘德华的忘情水”。一次唤醒一次交互", false);
    }


    /**
     * 唤醒回调
     */
    private WakeupListener wakeupListener = (angle, beam, score, keyWord) -> {
        //唤醒时停止播放tts
        AiuiEngine.TTS_stop();
        setText(mNlpText, "唤醒成功,angle:" + angle + " beam:" + beam + " score=" + score, false);
        setText(mNlpText, "唤醒词" + keyWord, false);
    };

    private void createTMEMusicRemote() {
        if (null == mTMERemote) {
            mTMERemote = TmeMusicRemote.Companion.createInstance(tmeSDKParams);
            // 酷狗SDK日志开关 ：true 打开，false 关闭
            mTMERemote.setDebug(true);
            // 查询激活状态
            mTMERemote.queryIsActivated(res -> {
                if (res) {
                    isActivated = res;
                    ActivatedBtn.setText("已激活");
                } else {
                    ActivatedBtn.setText("点击激活");
                }
                return null;
            });

            if (null != mTMERemote) {
                setText(mNlpText, "TMEMusicRemote 初始化成功", false);
                ActivatedBtn.setEnabled(true);
                LoginBtn.setEnabled(true);
                LogoutBtn.setEnabled(true);
            }

        }
    }

    private void createAIUIPlayer() {
        if (null == mAIUIPlayer) {
            mAIUIPlayer = new AIUIPlayer(this, tmeSDKParams);
            // 播放前焦点占用设置
            mAIUIPlayer.setParameter("customAudioFocus", "true");
            // 回调信息设置
            mAIUIPlayer.addListener(mPlayListener);
            // AIUIPlayer SDK调试日志设置 ：true 打开，false 关闭
            mAIUIPlayer.setDebug(true);
            // 初始化播放器
            mAIUIPlayer.initialize();
            setText(mNlpText, "AIUIPlayer 初始化成功", false);

        }
    }

    private void initAIUI() {
        //状态初始化
        EngineConstants.isRecording = false;
        // 初始化AIUI(识别+语义+合成）
        mAIUIAgent = AiuiEngine.getInstance(mAIUIListener, aiuiCfgPath);
        if (mAIUIAgent != null) {
            setText(mNlpText, "AIUI初始化成功", false);
            Log.i(TAG, "AIUI初始化成功");
        } else {
            setText(mNlpText, "AIUI初始化失败", false);
            Log.e(TAG, "AIUI初始化失败");
        }
    }

    private void releaseSDK() {
        mPlayList = null;
        setText(mNlpText, "", true);
        destroyTMERemote();
        destroyAIUIPlayer();
        AiuiEngine.destroy();
    }

    private void destroyTMERemote() {
        if (null != mTMERemote) {
            mTMERemote.destroy();
            mTMERemote = null;
            runBtnUiTread(ActivatedBtn, false);
            runBtnUiTread(LoginBtn, false);
            runBtnUiTread(LogoutBtn, false);
            setText(mNlpText, "TMEMusicRemote-SDK 销毁成功\n", false);
        }
    }

    private void destroyAIUIPlayer() {
        if (null != mAIUIPlayer) {
            mAIUIPlayer.release();
            mAIUIPlayer = null;
            runBtnUiTread(PreBtn, false);
            runBtnUiTread(NextBtn, false);
            runBtnUiTread(PlayOrStopBtn, false);
            runBtnUiTread(PauseOrResumeBtn, false);
            setText(mNlpText, "AIUIPlayer-SDK 销毁成功\n", false);
        }
    }


    private void startRecord() {
        if (recorder != null) {
            int ret = recorder.startRecord();
            if (0 == ret) {
                setText(mNlpText, "开启录音成功！", false);
            } else if (111111 == ret) {
                setText(mNlpText, "异常,AlsaRecorder is null ...", false);
            } else {
                setText(mNlpText, "开启录音失败，请查看/dev/snd/下的设备节点是否有777权限！\nAndroid 8.0 以上需要暂时使用setenforce 0 命令关闭Selinux权限！", false);
                destroyRecord();
            }
        }
    }

    private void stopVoiceNlp() {
        if (null == mAIUIAgent) {
            showTip("AIUIAgent 为空，请先初始化SDK");
            return;
        }

        Log.i(TAG, "stop voice nlp");
        // 停止录音
        String params = "sample_rate=16000,data_type=audio";
        AIUIMessage stopRecord = new AIUIMessage(AIUIConstant.CMD_STOP_RECORD, 0, 0, params, null);

        mAIUIAgent.sendMessage(stopRecord);
    }

    private void destroyRecord() {
        stopRecord();
        recorder = null;
        Log.d(TAG, "destroy is Done!");
    }

    private void stopRecord() {
        if (recorder != null) {
            recorder.stopRecord();
            setText(mNlpText, "停止录音", false);
        }
    }

    private void activate() {
        if (isActivated) {
            showToast("当前设备已激活TME音乐");
            return;
        }
        mTMERemote.activate(() -> {
            Log.i(TAG, "激活成功");
            ActivatedBtn.setText("已激活");
            return null;
        }, (errCode, errInfo) -> {
            Log.i(TAG, "激活失败，错误码为：" + errCode + " ,信息为： " + errInfo);
            return null;
        });
    }

    private void login() {
        Log.d(TAG, "login");
        //
        Intent intent = new Intent();
        intent.setAction("com.nova.ui.music.LoginKugouActivity");
        startActivityForResult(intent, 3);
//        Intent intent = new Intent(KugouDemo.this, LoginKugouActivity.class);
//        startActivityForResult(intent, 3);
    }

    private void logout() {
        mTMERemote.kugouLogout(new Function0<Unit>() {
            @Override
            public Unit invoke() {
                Log.i(TAG, "酷狗账号退出成功");
                LoginBtn.setText("手机登陆");
                return null;
            }
        }, new Function2<Integer, String, Unit>() {
            @Override
            public Unit invoke(Integer errCode, String errInfo) {
                Log.i(TAG, "酷狗账号退出失败，错误码为：" + errCode + " ,信息为： " + errInfo);
                return null;
            }
        });
    }

    private void last() {
        if (!mAIUIPlayer.previous()) {
            showToast("当前已是第一首");

        }
    }

    private void next() {
        if (!mAIUIPlayer.next()) {
            showToast("当前已是最后一首");
        }
    }

    private void controlPlayOrStop() {
        if (PlayOrStopBtn.getText().equals("播放")) {
            startPlayMusic();
        } else {
            mAIUIPlayer.stop();
        }
    }

    private void controlPauseOrResume() {
        if (mAIUIPlayer.getCurrentState() == PlayState.PLAYING) {
            mAIUIPlayer.pause();
        } else {
            mAIUIPlayer.resume();
        }
    }

    private void startPlayMusic() {
        if (null == mPlayList || mPlayList.length() == 0) {
            showToast("播放列表为空");
            return;
        }
        Log.i(TAG, "mPlayList is:\n" + mPlayList.toString());
        mAIUIPlayer.reset();
        mAIUIPlayer.play(mPlayList, "musicX", "", false, playListIndex);
    }


    //构建虚假播放信息测试AIUIPlayer SDK播放是否可以正常调用
    private void mockPlayMusic() {
        try {
            JSONArray musiclist = new JSONArray();
            JSONObject music = new JSONObject();
            music.put("source", "tme");
            music.put("songname", "天地龙鳞");
            music.put("itemid", "353833243");
            musiclist.put(0, music);
            mPlayList = musiclist;
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (null == mPlayList || mPlayList.length() == 0) {
            showToast("播放列表为空");
            return;
        }
        Log.i(TAG, "mPlayList is:\n" + mPlayList.toString());
        mAIUIPlayer.reset();
        mAIUIPlayer.play(mPlayList, "musicX", "", false, playListIndex);
    }

    private PlayerListener mPlayListener = new PlayerListener() {
        @Override
        public void onPlayerReady() {
            PlayOrStopBtn.setEnabled(true);
        }

        @Override
        public void onStateChange(@NonNull PlayState state) {
            Log.i(TAG, "PlayState is" + state.toString());
            switch (state) {
                case READY:
                    PlayOrStopBtn.setText("播放");
                    PreBtn.setEnabled(false);
                    NextBtn.setEnabled(false);
                    PauseOrResumeBtn.setEnabled(false);
                    break;
                case PLAYING:
                    PlayOrStopBtn.setText("停止");
                    PauseOrResumeBtn.setText("暂停");
                    PreBtn.setEnabled(true);
                    NextBtn.setEnabled(true);
                    PauseOrResumeBtn.setEnabled(true);
                    break;
                case PAUSED:
                    PlayOrStopBtn.setText("停止");
                    PauseOrResumeBtn.setText("继续");
                    break;
                case LOADING:
                    PlayOrStopBtn.setText("停止");
                    break;
                case COMPLETE:
                    PauseOrResumeBtn.setText("继续");
                    startPlayMusic();
                    break;
                case IDLE:
                    PreBtn.setEnabled(false);
                    NextBtn.setEnabled(false);
                    PlayOrStopBtn.setEnabled(false);
                    PauseOrResumeBtn.setEnabled(false);
                    break;
                case ERROR:
                    PlayOrStopBtn.setText("播放");
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onMediaChange(@NonNull MetaItem metaItem) {
            String songName = metaItem.getTitle();      //歌名
            String author = metaItem.getAuthor();      //作者
            playListIndex = getPlayIndex(songName);
        }

        @Override
        public void onMediaUrl(@NonNull JSONObject jsonObject) {
        }

        @Override
        public void onError(int code, @NonNull String info) {
            Log.e(TAG, "播放出错：" + code + " ，错误信息为：" + info);
            // 真实错误码需要从 info 中解析   "track link failed code: 40006 description:"
            if (info.isEmpty()) {
                if (code == 200001) {
                    setText(mNlpText, "歌曲\"" + SONG_NAME + "\"播放出错: " + code + "\nINFO：产品未通过酷狗验收,仅支持获取奇数id资源\n", false);
                    if (!mAIUIPlayer.next()) {
                        return;
                    }
                }
            } else {
                String[] split = info.split(" ");
                String errCode = split[4];
                switch (errCode) {
                    case "40000":
                        setText(mNlpText, "播放出错: " + errCode + "\n设备音乐装机量超限", false);
                        break;
                    case "40001":
                        setText(mNlpText, "播放出错: " + errCode + "\n设备激活限制", false);
                        break;
                    case "40004":
                        setText(mNlpText, "播放出错: " + errCode + "\n设备音乐未激活", false);
                        break;
                    case "40006":
                        setText(mNlpText, "播放出错: " + errCode + "\n酷狗用户账号未登陆绑定", false);
                        break;
                    case "40007":
                        setText(mNlpText, "播放出错: " + errCode + "\n厂商ID与设备当前绑定用户ID不一致", false);
                        break;
                    default:
                        setText(mNlpText, "播放出错: " + errCode + "  错误码查询：https://www.yuque.com/iflyaiui/zzoolv/rft07m", false);
                        break;
                }
            }
        }

        @Override
        public void onPlayerRelease() {
            PreBtn.setEnabled(false);
            NextBtn.setEnabled(false);
            PlayOrStopBtn.setEnabled(false);
            PauseOrResumeBtn.setEnabled(false);
        }
    };

    // 获取当前播放下标
    private int getPlayIndex(String songName) {
        if (mPlayList != null) {
            try {
                String playData = null;
                for (int i = 0; i < mPlayList.length(); i++) {
                    playData = mPlayList.getJSONObject(i).toString();
                    if (playData.contains(songName)) {
                        return i;
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                return 0;
            }
        }
        return 0;
    }

    private AIUIListener mAIUIListener = new AIUIListener() {

        @Override
        public void onEvent(AIUIEvent event) {
            switch (event.eventType) {
                case AIUIConstant.EVENT_CONNECTED_TO_SERVER:
                    showTip("已连接服务器");
                    break;

                case AIUIConstant.EVENT_WAKEUP:
                    showTip("进入识别状态");
                    setText(mNlpText, "开始识别...", false);
                    break;

                case AIUIConstant.EVENT_RESULT: {
                    //处理语音合成结果
                    if (event.info.contains("\"sub\":\"tts")) {
                        //无意义词不处理
                        if (event.data.getString("sid").equals(senselessWordUtil.nonsenseSid)) {
                            AiuiEngine.TTS_stop();
                            return;
                        }
                        //保存云端的tts音频文件，用于离线播放
                        if (EngineConstants.saveTTS) {
                            byte[] audio = event.data.getByteArray("0"); //tts音频数据，16k，16bit格式
                            FileUtil.writeFile(audio, "/sdcard/tts.pcm");
                        }

                        //如果使用sdk的播放器合成，可以不用解析tts
                        return;

                        //开发者自己用播放器来合成
//                    byte[] audio=event.data.getByteArray("0");//tts音频数据，16k，16bit格式
//                    超过500ms静音，认为是无效音频，进行过滤
//                    byte[] filteredAudio=TtsFilterUtil.filter(audio,500);
                    }
                    //处理识别结果
                    if (event.info.contains("\"sub\":\"iat")) {
                        com.alibaba.fastjson.JSONObject cntJson = JSON.parseObject(new String(event.data.getByteArray("0"), StandardCharsets.UTF_8));
                        if (cntJson == null) {
                            return;
                        }
                        com.alibaba.fastjson.JSONObject text = cntJson.getJSONObject("text");
                        //识别结果
                        String asrResult = StreamingAsrUtil.processIATResult(text);
                    }
                    try {
                        if (event.info.contains("\"sub\":\"nlp")) {
                            JSONObject cntJson = new JSONObject(new String(event.data.getByteArray("0"), StandardCharsets.UTF_8));
                            JSONObject nlpResult = cntJson.getJSONObject("intent");
                            Log.d(TAG, nlpResult.toString());
                            String asrResult = nlpResult.getString("text");
                            setText(mNlpText, "识别结果:" + asrResult, false);
                            try {
                                String service = nlpResult.getString("service");
                                if (service.equals("musicX")) {
                                    //获取歌曲返回结果
                                    JSONObject data = nlpResult.getJSONObject("data");
                                    JSONArray res_music = data.getJSONArray("result");
                                    if (null != res_music) {
                                        mPlayList = res_music;
                                        playListIndex = 0;
                                    }
                                    startPlayMusic();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                }
                break;

                case AIUIConstant.EVENT_ERROR: {
                    setText(mNlpText, "错误: " + event.arg1 + "\n" + event.info + "\n", false);
                }
                break;
                case AIUIConstant.EVENT_STATE: {    // 状态事件
                    EngineConstants.mAIUIState = event.arg1;
                }
                break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mAIUIPlayer) {
            mAIUIPlayer.release();
            mAIUIPlayer = null;
        }
        if (null != mTMERemote) {
            mTMERemote.destroy();
            mTMERemote = null;
        }
        //销毁唤醒引擎
        WakeupEngine.destroy();
        //销毁aiui
        AiuiEngine.destroy();
    }

    private void showTip(final String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mToast.setText(str);
                mToast.show();
            }
        });
    }

    private void showToast(String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!TextUtils.isEmpty(message)) {
                    Timber.d(message);
                    Toast.makeText(KugouDemo.this, message, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void changeWakeupStatus() {
        EnableWakeup = !EnableWakeup; //切换状态
        if (EnableWakeup) {
            EnableWakeupBtn.setText("语音唤醒已开启");
            SystemRecorder.AUDIO_TYPE_ASR = false;
        } else {
            EnableWakeupBtn.setText("语音唤醒已关闭");
            SystemRecorder.AUDIO_TYPE_ASR = true;
        }
    }

    private void runBtnUiTread(Button btn, Boolean bool) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                btn.setEnabled(bool);
            }
        });
    }

    private void setText(TextView view, String showText, Boolean iFSetText) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (iFSetText) {
                    view.setText(showText);
                } else {
                    view.append("\n");
                    view.append(showText);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 3 && resultCode == Activity.RESULT_OK) {
            showToast("手机登录成功");
            // 获取数据
//			String expire = data.getStringExtra("expire");
//			String userid = data.getStringExtra("userid");
//			String token = data.getStringExtra("token");
        }
    }

    /**
     * 申请权限
     */
    private void requestPermissions() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                ActivityCompat.requestPermissions(this, new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.INTERNET}, 0x0010);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**********************************************权限请求******************************************************/
    private void requiresPermission() {
        XXPermissions.with(this)
                .permission(Permission.RECORD_AUDIO)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (!all) {
                            Log.d("test", "获取部分权限成功，但部分权限未正常授予");
//                            ToastUtils.show("获取部分权限成功，但部分权限未正常授予");
                            return;
                        } else {
                            Log.d("test", "获取权限成功");
                            initSDK();
                        }

                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                    }
                });

    }
}
